package com.lsh.payment.service.alipay;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.dubbo.rpc.RpcContext;
import com.alibaba.dubbo.rpc.protocol.rest.support.ContentType;
import com.alibaba.fastjson.JSON;
import com.lsh.payment.api.service.aliPay.IAliPayRestService;
import com.lsh.payment.core.constant.BusinessConstant;
import com.lsh.payment.core.exception.BusinessException;
import com.lsh.payment.core.model.payment.PayDeal;
import com.lsh.payment.core.service.alipay.IAliNotifyService;
import com.lsh.payment.core.service.paylog.PayLogService;
import com.lsh.payment.core.util.HttpParamsUntil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import java.util.Map;

/**
 * Project Name: lsh-payment
 * Created by jingyuan
 * Date: 16/10/31
 * 北京链商电子商务有限公司
 * Package com.lsh.payment.service.qfPay
 * desc:
 *
 * @author peter
 */
@Service(protocol = "rest")
@Path("alipay")
@Produces({ContentType.TEXT_PLAIN_UTF_8})
public class AliPayRestServiceImpl implements IAliPayRestService {

    private final static String CHARSET = "UTF-8";

    @Autowired
    private IAliNotifyService aliNotifyService;

    @Autowired
    private PayLogService payLogService;

    private Logger logger = LoggerFactory.getLogger(AliPayRestServiceImpl.class);

    @Override
    @Path("notify")
    @POST
    public String aliNotify() {
        HttpServletRequest request = (HttpServletRequest) RpcContext.getContext().getRequest();

        String aliPayResponse;

        try {
            request.setCharacterEncoding(CHARSET);
            Map<String, String> requestMap = HttpParamsUntil.getAlipayParamMap(request);
            logger.info("支付宝回调请求参数:" + JSON.toJSONString(requestMap));
            logger.info("支付宝回调,sign:{},trade_status:{}", requestMap.get("sign"), requestMap.get("trade_status"));
            PayDeal payDeal = aliNotifyService.notifyHandle(requestMap);
            aliPayResponse = BusinessConstant.OPERATE_SUCCESS_STRING;

            //入日志表
            if (payDeal != null) {
                payLogService.insertLog(payDeal.getPayId(), payDeal.getPayPaymentNo(), payDeal.getTradeId(), BusinessConstant.LOG_PAY_TYPE_PAY_NOTIFY,
                        BusinessConstant.OPERATE_SUCCESS, JSON.toJSONString(requestMap), aliPayResponse, payDeal.getVenderId());
            }
        } catch (BusinessException e) {

            aliPayResponse = BusinessConstant.OPERATE_FAIL_STRING;
            logger.error("业务异常:" + e.getCode() + e.getMessage());
        } catch (Exception e) {

            aliPayResponse = BusinessConstant.OPERATE_FAIL_STRING;
            logger.error("服务端异常", e);
        }

//        this.monitor(request, aliPayResponse, beginTime);

        return aliPayResponse;
    }


//    /**
//     * 监控
//     *
//     * @param request        请求参数
//     * @param aliPayResponse 返回值
//     * @param beginTime      开始时间
//     */
//
//    private void monitor(HttpServletRequest request, String aliPayResponse, long beginTime) {
//        try {
//            long wasteTime = System.currentTimeMillis() - beginTime;
//            logger.info("支付宝回调接口耗时 {} 毫秒。", wasteTime);
//            String wasteTimeStr = (new StringBuffer(DateUtil.nowStrFormate())).append("[").append(wasteTime).append("]").toString();
//            PayMonitorInterfaceModel payMonitorInterfaceModel = new PayMonitorInterfaceModel(request, wasteTimeStr, this.getClass().getSimpleName());
//            if (BusinessConstant.OPERATE_FAIL_STRING.equals(aliPayResponse)) {
//                payMonitorInterfaceModel.setResultFlag(false);
//            }
//            PayEventBus.post(payMonitorInterfaceModel);
//        } catch (Throwable e) {
//            logger.error("收集监控信息失败", e);
//        }
//    }


}

